<template>
  <a-range-picker
    :size="size"
    v-model:value="modelValue"
    :placeholder="placeholder"
    :format="format"
    :valueFormat="format"
    :allowClear="allowClear"
    :disabled="disabled"
    @change="handleChange"
  />
</template>
<script lang="ts" setup>
  import { ref, watchEffect, inject, watch } from 'vue';

  const props = defineProps({
    value: Array,
    size: String,
    placeholder: Array,
    format: String,
    allowClear: Boolean,
    disabled: Boolean,
    startField: String,
    endField: String,
    //子表名
    mainKey: String,
    //组件在子表中的Index
    tableIndex: Number,
  });

  const formModel = inject<any>('formModel', null);
  const modelValue = ref<string[]>([]);
  const emit = defineEmits(['update:value', 'change']);
  watch(
    () => props.value,
    (val: any) => {
      modelValue.value = val || [];
    },
    {
      immediate: true,
    },
  );

  watchEffect(() => {
    // if (!props.value) {
    //   emit('update:value', []);
    //   return;
    // }
    if (props.mainKey) {
      if (!formModel[props.mainKey]) return;
      const emitData =
        !formModel[props.mainKey][props.tableIndex!]?.[props.startField!] ||
        !formModel[props.mainKey][props.tableIndex!]?.[props.endField!]
          ? null
          : [
              formModel[props.mainKey][props.tableIndex!]?.[props.startField!],
              formModel[props.mainKey][props.tableIndex!]?.[props.endField!],
            ];
      emit('update:value', emitData);
    } else {
      if (props.startField && props.endField && Object.keys(formModel).length) {
        const emitData =
          !formModel[props.startField] || !formModel[props.endField]
            ? null
            : [formModel[props.startField], formModel[props.endField]];
        emit('update:value', emitData);
      }
    }
  });
  const handleChange = (time) => {
    emit('update:value', time);
    emit('change', time);
    if (formModel && props.startField && props.endField) {
      if (props.mainKey) {
        formModel[props.mainKey][props.tableIndex!][props.startField!] = time?.length
          ? time[0]
          : '';
        formModel[props.mainKey][props.tableIndex!][props.endField!] = time?.length ? time[1] : '';
      } else {
        formModel[props.startField!] = time?.length ? time[0] : '';
        formModel[props.endField!] = time?.length ? time[1] : '';
      }
    }
  };
</script>
